Kotlin 中的 Python list、set 和 map comprehension 等价于什么?

What is the equivalent of Python list, set, and map comprehensions in Kotlin?

在 Python 中,有列表推导式和类似的映射和集合结构。在 Kotlin 中,任何具有相似名称的文档中都没有任何内容。

这些理解的等价物是什么?例如,在 Python 3 Patterns, Recipes and Idioms 中找到的那些。其中包括对以下内容的理解:

注: 此问题是作者(Self-Answered Questions)特意写下并回答的,以便常见问题的 Kotlin 主题的惯用答案出现在 SO 中。

Python 3 Patterns, Recipes and Idioms 中获取示例,我们可以使用简单的模式将每个示例转换为 Kotlin。 Python 版本的列表理解有 3 个部分:

  1. 输出表达式
  2. 输入list/sequence和变量
  3. 可选谓词

这些与 Kotlin 对集合的功能扩展直接相关 类。输入序列,后跟 filter lambda 中的可选谓词,后跟 map lambda 中的输出表达式。所以对于这个 Python 例子:

# === PYTHON

a_list = [1, 2, 3, 4, 5, 6]

#                    output | var | input   | filter/predicate 
even_ints_squared = [ e*e  for e in a_list  if e % 2 == 0 ]

print(even_ints_squared)
# output: [ 4, 16, 36 ]

变成

// === KOTLIN

var aList = listOf(1, 2, 3, 4, 5, 6)

//                    input      |   filter      |       output              
val evenIntsSquared = aList.filter { it % 2 == 0 }.map { it * it }

println(evenIntsSquared)
// output: [ 4, 16, 36 ]  

请注意,Kotlin 版本不需要该变量,因为在每个 lambda 中都使用了隐含的 it 变量。在 Python 中,您可以使用 () 而不是方括号将它们变成惰性生成器:

# === PYTHON

even_ints_squared = ( e**2 for e in a_list if e % 2 == 0 )

而在 Kotlin 中,通过函数调用更改输入更明显地将其转换为惰性序列 asSequence():

// === KOTLIN

val evenIntsSquared = aList.asSequence().filter { it % 2 == 0 }.map { it * it }

Kotlin 中的嵌套理解是通过将一个嵌套在另一个 map lambda 中创建的。例如,将 Python 中的 PythonCourse.eu 中的示例稍微更改为同时使用集合和列表理解:

# === PYTHON

noprimes = {j for i in range(2, 8) for j in range(i*2, 100, i)}
primes = [x for x in range(2, 100) if x not in noprimes]
print(primes)
# output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

变为:

// === KOTLIN

val nonprimes = (2..7).flatMap { (it*2..99).step(it).toList() }.toSet()
val primes = (2..99).filterNot { it in nonprimes }
print(primes)    
// output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

请注意,嵌套理解生成一个列表列表,该列表使用 flatMap() 转换为平面列表,然后使用 toSet() 转换为集合。此外,Kotlin 范围是包容性的,而 Python 范围是排他性的,因此您会看到范围内的数字略有不同。

您还可以在 Kotlin 中使用带有协同例程的 sequence 生成器来生成值,而无需调用 flatMap()flatten():

// === KOTLIN

val nonprimes = sequence {
    (2..7).forEach { (it*2..99).step(it).forEach { value -> yield(value) } }
}.toSet()
val primes = (2..99).filterNot { it in nonprimes }

引用的 Python 页面中的另一个示例正在生成矩阵:

# === PYTHON

matrix = [ [ 1 if item_idx == row_idx else 0 for item_idx in range(0, 3) ] for row_idx in range(0, 3) ]
print(matrix)
# [[1, 0, 0], 
#  [0, 1, 0], 
#  [0, 0, 1]] 

在 Kotlin 中:

// === KOTLIN

val matrix = (0..2).map { row -> (0..2).map { col -> if (col == row) 1 else 0 }}
println(matrix)
// [[1, 0, 0], 
//  [0, 1, 0], 
//  [0, 0, 1]]  

或者在 Kotlin 中而不是列表中,您还可以生成数组:

// === KOTLIN

val matrix2 = Array(3) { row -> 
                          IntArray(3) { col -> if (col == row) 1 else 0 } 
                       }

集合理解的另一个示例是生成一组唯一的正确大小写的名称:

# === PYTHON

names = [ 'Bob', 'JOHN', 'alice', 'bob', 'ALICE', 'J', 'Bob' ]

fixedNames = { name[0].upper() + name[1:].lower() for name in names if len(name) > 1 }

print(fixedNames)
# output: {'Bob', 'Alice', 'John'}

翻译成 Kotlin:

// === KOTLIN

val names = listOf( "Bob", "JOHN", "alice", "bob", "ALICE", "J", "Bob" )

val fixedNames = names.filter { it.length > 1 }
       .map { it.take(1).toUpperCase() + it.drop(1).toLowerCase() }
       .toSet()

println(fixedNames)
// output: [Bob, John, Alice]

地图理解的例子有点奇怪,但也可以在 Kotlin 中实现。原文:

# === PYTHON

mcase = {'a':10, 'b': 34, 'A': 7, 'Z':3}

mcase_frequency = { k.lower() : mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys() }

print(mcase_frequency)
# output: {'a': 17, 'z': 3, 'b': 34}

和转换后的,这里写得更"wordy"是为了更清楚是怎么回事:

// === KOTLIN

val mcase = mapOf("a" to 10, "b" to 34, "A" to 7, "Z" to 3)

val mcaseFrequency = mcase.map { (key, _) ->
    val newKey = key.toLowerCase()
    val newValue = mcase.getOrDefault(key.toLowerCase(), 0) +
                   mcase.getOrDefault(key.toUpperCase(), 0)
    newKey to newValue
}.toMap()

print(mcaseFrequency)
// output: {a=17, b=34, z=3}

延伸阅读:

val newls = (1..100).filter({it % 7 == 0})

在 Kotlin 中相当于下面的 Python 代码

newls = [i for i in 0..100 if i % 7 ==0]

只是为了练习,最接近 python 的是:

infix fun <I, O> ((I) -> O).`in`(range: Iterable<I>): List<O> = range.map(this).toList()
infix fun <I> Iterable<I>.`if`(cond: (I) -> Boolean): List<I> = this.filter(cond)

fun main() {
    { it: Int -> it + 1 } `in` 1..2 `if` {it > 0}
}